<?php
/**
 * Created by JetBrains PhpStorm.
 * User: heimuya
 * Date: 14-1-26
 * Time: 下午1:33
 * 监控中心控制器类
 */
class WatchAction extends AdminAction{
	
	public function _initialize(){
		parent::_initialize();
		$this->assign('page', __CLASS__);
	}
	
    /**
     * 机台管理
     */
    public function machines(){
		$this->assign('method', 'machines');
		$this->assign('storelist', D("Store")->field('id,name')->order('id desc')->select());
        $this->display();
    }
	
    /**
     * 机台管理
     */
    public function macstatus(){
		$this->assign('method', 'macstatus');
        $this->display();
    }
	
    /**
     * 机台连接设置
     */
    public function macset(){
        $type = $this->_get('type');
        switch($type){
            case 1:
                $errorMsg = L('currentpwdError');
                break;
            case 2:
                $errorMsg = L('saveSuccess');
                break;
            default:
                $errorMsg = '';
                break;
        }
        $this->assign('errorMsg', $errorMsg);
		
    	$set = M('System')->field('value')->where(array('name' => 'connectday'))->find();
		
		$this->assign('connectday', $set['value']);
		$this->assign('method', 'macset');
        $this->display();
    }
	 
    /**
     * 机台连接设置
     */
    public function connset(){
    	$postData = $this->_post();
		//判断密码是否正确
		$user = D('User');
        if(!($userInfo = $user->getUserInfo(session('unick'))) || $userInfo['password'] != md5($postData['currentpassword'])){//用户名或者密码错误
            $this->redirect('Watch/macset', array('type' => 1));
			exit(0);
        }
		
    	M('System')->where(array('name' => 'connectday'))->save(array('value' => $postData['day'], 'time' => time()));
		$this->redirect('Watch/macset', array('type' => 2));
		exit(0);
    }
	
	/**
	 * 异步获取机台数据
	 */
	 public function machinesjson(){
	 	$aColumns = array('id', 'number', 'store', 'updatetime', 'valid', 'act');
	 	$getdata = $this->_get();
		
		$order = "";
		if (isset($getdata['iSortCol_0'])){
			for ($i=0 ; $i<intval( $getdata['iSortingCols'] ) ; $i++){
				if ($getdata[ 'bSortable_'.intval($getdata['iSortCol_'.$i]) ] == "true"){
					if($aColumns[intval( $getdata['iSortCol_'.$i] ) ] == 'act' || $aColumns[intval( $getdata['iSortCol_'.$i] ) ] == 'nick' || $aColumns[intval( $getdata['iSortCol_'.$i] ) ] == 'name'){
						continue;
					}
					$order .= "`".$aColumns[intval( $getdata['iSortCol_'.$i] ) ]."` ".
						($getdata['sSortDir_'.$i]==='asc' ? 'asc' : 'desc') .", ";
				}
			}
			$order = substr_replace( $order, "", -2 );
	 	}
		$map = array();
		if (isset($getdata['sSearch']) && $getdata['sSearch'] != ""){
			$map['number'] = array('like', '%'.$getdata['sSearch'].'%');
		}
		
		$result = $this->pageList_dataTable(D('Machine'), $getdata, $map, '', $order);
		
		$output = array(
			'sEcho'					=> intval($getdata['sEcho']),
			'iTotalRecords'			=> D('Machine')->count(),//除掉当前登录用户自己
			'iTotalDisplayRecords'	=> $result['count'],
			'aaData'				=> array()
		);
		
		$storeList = changeArrayKey(D("Store")->field('id,name')->select());
		
		foreach ($result['list'] as $key => $value) {
			$row = array();
			for($i = 0; $i < count($aColumns); $i++){
				if($aColumns[$i] == 'store'){
					$row[] = '<input type="hidden" value="'.$value['store'].'" name="store" />'.$storeList[$value['store']]['name'];//店铺名称
				}else if($aColumns[$i] == 'act'){
					$row[] = '<a href="#" class="btn blue icn-only"><i class="icon-edit"></i></a>  '.
							'<a href="#" class="btn red icn-only"><i class="icon-remove icon-white"></i></a>';
				}else if($aColumns[$i] == 'updatetime'){
					if($value['updatetime'] == '' || $value['updatetime'] == NULL){
						$row[] = '';
					}else{
						$row[] = date('Y-m-d H:i:s', $value['updatetime']);
					}
				}else if($aColumns[$i] == 'valid'){
					if($value['valid'] === 'n'){
						$row[] = '<input type="hidden" value="'.$value['valid'].'" name="valid" /><span class="red">'.L('no').'</span>';
					}else{
						$row[] = '<input type="hidden" value="'.$value['valid'].'" name="valid" />'.L('yes');
					}
				}else{
					$row[] = $value[$aColumns[$i]];
				}
			}
			$output['aaData'][] = $row;
		}

		echo json_encode($output);
		exit(0);
	 }

	/**
	 * 异步获取机台状态数据
	 */
	 public function macstatusjson(){
	 	$aColumns = array('number', 'uid', 'store', 'updatetime', 'status', 'unconnectday');
	 	$getdata = $this->_get();
		
		$order = "";
		if (isset($getdata['iSortCol_0'])){
			for ($i=0 ; $i<intval( $getdata['iSortingCols'] ) ; $i++){
				if ($getdata[ 'bSortable_'.intval($getdata['iSortCol_'.$i]) ] == "true"){
					if($aColumns[intval( $getdata['iSortCol_'.$i] ) ] == 'unconnectday'){
						$order .= "`updatetime` ".
							($getdata['sSortDir_'.$i]==='asc' ? 'desc' : 'asc') .", ";
					}else{
						$order .= "`".$aColumns[intval( $getdata['iSortCol_'.$i] ) ]."` ".
							($getdata['sSortDir_'.$i]==='asc' ? 'asc' : 'desc') .", ";
					}
				}
			}
			$order = substr_replace( $order, "", -2 );
	 	}
		
		$type = $getdata['sSearch_3'];//查看类型
		$smap['name|number'] = array('like', '%'.$getdata['sSearch'].'%');//模糊搜索店铺
		$storeList = changeArrayKey(D("Store")->where($smap)->field('id,name')->select());
		$storeid = array();
		foreach ($storeList as $skey => $svalue) {
			$storeid[] = intval($svalue['id']);
		}
		$map = array();
		if (isset($getdata['sSearch']) && $getdata['sSearch'] != ""){
			$where['number'] = array('like', '%'.$getdata['sSearch'].'%');
			$where['store'] = array('in', $storeid);
			$where['_logic'] = 'or';
			$map['_complex'] = $where;
		}
		
		$today = strtotime(date('Y-m-d', time()));
		if($type === '1'){
			$map['updatetime'] = array('lt', $today);
		}else if($type === '2'){
			$map['updatetime'] = array('lt', $today - 86400 * 3);
		}
		
		$result = $this->pageList_dataTable(D('Machine'), $getdata, $map, 'id,valid', $order);
		
		$output = array(
			'sEcho'					=> intval($getdata['sEcho']),
			'iTotalRecords'			=> D('Machine')->count(),//除掉当前登录用户自己
			'iTotalDisplayRecords'	=> $result['count'],
			'aaData'				=> array()
		);
		
		
		foreach ($result['list'] as $key => $value) {
			$row = array();
			for($i = 0; $i < count($aColumns); $i++){
				if($aColumns[$i] == 'store'){
					$row[] = $storeList[$value['store']]['name'];//店铺名称
				}else if($aColumns[$i] == 'unconnectday'){
					if(intval($value['updatetime']) > $today){
						$row[] = 0;
					}else{
						$unconnectday = floor(($today - intval($value['updatetime'])) / 86400);
						if($unconnectday >= 3){
							$row[] = '<span class="red">'.$unconnectday.'</span>';
						}else{
							$row[] = $unconnectday;
						}
					}
				}else if($aColumns[$i] == 'updatetime'){
					if($value['updatetime'] == '' || $value['updatetime'] == NULL){
						$row[] = '';
					}else{
						$row[] = date('Y-m-d H:i:s', $value['updatetime']);
					}
				}else if($aColumns[$i] == 'status'){
					if(intval($value['updatetime']) < $today){
						$row[] = '<span class="red">'.L('offline').'</span>';
					}else{
						$row[] = L('online');
					}
				}else{
					$row[] = $value[$aColumns[$i]];
				}
			}
			$output['aaData'][] = $row;
		}

		echo json_encode($output);
		exit(0);
	 }
		 
	/**
	 * 新增信息
	 */
	 public function create(){
	 	//异步提交的数据
		$postdata = $this->_post();
		switch ($postdata['method']) {
			case 'machines':
				$data['number'] = $postdata['number'];
				$data['store'] = $postdata['store'];
				$data['valid'] = $postdata['valid'];
				$data['updatetime'] = time() - 86400;
				D('Machine')->add($data);
				break;
			default:
				echo json_encode(array('status' => 201, 'errorMsg' => L('dataerror')));
				exit(0);
				break;
		}
		
		echo json_encode(array('status' => 200));
		exit(0);
	 }
	 
	/**
	 * 编辑信息
	 */
	 public function edit(){
	 	//异步提交的数据
	 	$postdata = $this->_post();
		switch ($postdata['method']) {
			case 'machines':
				$data['number'] = $postdata['number'];
				$data['store'] = $postdata['store'];
				$data['valid'] = $postdata['valid'];
				$where['id'] = $postdata['machineid'];
				D('Machine')->where($where)->save($data);
				break;
			default:
				echo json_encode(array('status' => 201, 'errorMsg' => L('dataerror')));
				exit(0);
				break;
		}
		
		echo json_encode(array('status' => 200));
		exit(0);
	 }
	 
	/**
	 * 删除信息
	 */
	 public function delete(){
	 	//异步提交的数据
	 	$trans = array(
			'machines'	=> 'Machine'
		);
	 	$postdata = $this->_post();
		
		$where['id'] = $postdata['id'];
		D($trans[$postdata['method']])->where($where)->delete();
		
		echo json_encode(array('status' => 200));
		exit(0);
	 }
}